"""
pytest 配置文件
"""

import pytest
import tempfile
import shutil
from pathlib import Path
from unittest.mock import Mock, patch
from md2dockit.app import create_app
from md2dockit.app.config import Config


class TestConfig(Config):
    """测试配置"""
    TESTING = True
    MONGO_URI = "mongodb://localhost:27017/md2dockit_test"
    REDIS_URL = "redis://localhost:6379/1"
    SECRET_KEY = "test-secret-key"
    UPLOAD_FOLDER = None  # 将在测试中设置
    OUTPUT_FOLDER = None  # 将在测试中设置
    TEMP_FOLDER = None    # 将在测试中设置


@pytest.fixture(scope="session")
def temp_dirs():
    """创建临时目录"""
    temp_base = tempfile.mkdtemp()
    temp_path = Path(temp_base)
    
    upload_dir = temp_path / "uploads"
    output_dir = temp_path / "outputs"
    temp_dir = temp_path / "temp"
    
    upload_dir.mkdir()
    output_dir.mkdir()
    temp_dir.mkdir()
    
    yield {
        'upload': str(upload_dir),
        'output': str(output_dir),
        'temp': str(temp_dir)
    }
    
    # 清理临时目录
    shutil.rmtree(temp_base)


@pytest.fixture
def app(temp_dirs):
    """创建测试应用"""
    TestConfig.UPLOAD_FOLDER = temp_dirs['upload']
    TestConfig.OUTPUT_FOLDER = temp_dirs['output']
    TestConfig.TEMP_FOLDER = temp_dirs['temp']
    
    app = create_app(TestConfig)
    
    with app.app_context():
        yield app


@pytest.fixture
def client(app):
    """创建测试客户端"""
    return app.test_client()


@pytest.fixture
def runner(app):
    """创建CLI测试运行器"""
    return app.test_cli_runner()


@pytest.fixture
def mock_mongo():
    """模拟MongoDB连接"""
    with patch('md2dockit.app.models.mongo') as mock:
        yield mock


@pytest.fixture
def mock_redis():
    """模拟Redis连接"""
    with patch('md2dockit.app.services.redis_client') as mock:
        yield mock


@pytest.fixture
def mock_celery():
    """模拟Celery任务"""
    with patch('md2dockit.app.tasks.convert_document.delay') as mock:
        mock.return_value = Mock(id='test-task-id')
        yield mock


@pytest.fixture
def sample_markdown_file(temp_dirs):
    """创建示例Markdown文件"""
    content = """# 测试文档

这是一个测试文档。

## 章节1

这是第一个章节的内容。

### 子章节1.1

这是子章节的内容。

## 章节2

这是第二个章节的内容。

- 列表项1
- 列表项2
- 列表项3

```python
def hello_world():
    print("Hello, World!")
```

**粗体文本** 和 *斜体文本*。
"""
    
    file_path = Path(temp_dirs['upload']) / "test.md"
    file_path.write_text(content, encoding='utf-8')
    
    return str(file_path)


@pytest.fixture
def sample_task_data():
    """示例任务数据"""
    return {
        'task_id': 'test-task-123',
        'filename': 'test.md',
        'original_filename': 'test.md',
        'file_size': 1024,
        'output_format': 'docx',
        'options': {
            'template': 'default',
            'css_theme': 'github',
            'page_size': 'A4',
            'include_toc': True
        },
        'status': 'pending',
        'progress': 0,
        'created_at': '2024-01-01T00:00:00Z'
    }